package com.itheima.sh.f_ajax_json_test_06;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

/**
 * @author stay foolish
 * @description 行至水穷处, 坐看云起时
 * @date 2022/11/19 0:38:09
 * @description TODD
 */
@WebServlet("/fastJsonDemo100Servlet")
public class FastJsonDemo100Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            // 处理前端的json数据并将其封装到java对象中
//        User user = JSON.parseObject(request.getInputStream(), User.class);
            User user = BaseController.jsonToPojo(request, User.class);
            System.out.println("user = " + user);
            // 创建多个user对象存入集合中
            ArrayList<User> list = new ArrayList<>();
            Collections.addAll(list, new User("玉米", "1234"),
                    new User("大豆", "2345"),
                    new User("水稻", "3456") );
            // 将java对象转化为json字符串
            // String jsonStr = JSON.toJSONString(list);
            // 创建Result对象,这里利用满参构造,因为是查询
            Result result = new Result(true,"查询成功",list);
            BaseController.printJsonToBrowser(result,response);

        } catch (Exception e) {
            e.printStackTrace();
            try {
                Result result = new Result(false,"失败");
                // 将jresult对象转化为json字符串
//        String jsonStr = JSON.toJSONString(result);
                BaseController.printJsonToBrowser(result,response);
            } catch (Exception ex) {
                e.printStackTrace();
            }
        }

        // 响应给前端浏览器
//        response.getWriter().write(jsonStr);

    }
}

